package com.example.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alipay.sdk.app.PayTask;
import com.example.util.PayResult;

import java.util.Map;

/**
 *
 */
public class AlipayActivity extends AppCompatActivity {
    private static final String TAG = "AlipayActivity";
    private String orderInfo = "";
    public final static int PAY_CODE = 0x06;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderInfo = getIntent().getStringExtra("order");
        //因通过H5获取的订单数据，需要把双引号处理掉
        orderInfo =  orderInfo.substring(1,orderInfo.length()-1);
        aliPay();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case PAY_CODE:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String status = payResult.getResultStatus();
                    String result = payResult.getResult();
                    if(status.equals("9000")){
                        Toast.makeText(AlipayActivity.this,"支付成功",Toast.LENGTH_SHORT).show();

                    }else{
                        Toast.makeText(AlipayActivity.this,"支付失败",Toast.LENGTH_SHORT).show();
                    }

                    AlipayActivity.this.finish();

                    break;
            }
        }
    };

    /**
     *
     */
    private void aliPay(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //Log.i(TAG,"order:"+orderInfo);

                PayTask alipay = new PayTask(AlipayActivity.this);
                Map<String,String> result = alipay.payV2(orderInfo,true);

                Message msg = new Message();
                msg.what = PAY_CODE;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(runnable);
        payThread.start();
    }

}
